package com.client;

import java.util.Date;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Cookies;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Anchor;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.datepicker.client.CalendarUtil;
import com.shared.TaskGrid;
import com.shared.Token;

public class EntryPointMain implements EntryPoint {   // Version : $Revision$  
  private final ServiceAsync gtiService = GWT.create(Service.class);
  private final Logger      log         = Logger.getLogger("");
  private       String      code;
  private       String      tokenAccess;
  private       String      tokenRefresh;
  private final Token       token       = new Token ();

  public void onModuleLoad() {      
   log.log(Level.INFO, "gtask search start"); // add '?logLevel=INFO' to see that logLevel
  
   GWT.UncaughtExceptionHandler uncaughtExceptionHandler = new GWT.UncaughtExceptionHandler() {
      public void onUncaughtException(Throwable e) {              
          String msg;              
          msg = e.getMessage ();             
          for (StackTraceElement se : e.getStackTrace()) {
              msg += "\n   " + se.toString();                
          }
          log.log(Level.SEVERE, msg);
      }
   };           
   GWT.setUncaughtExceptionHandler(uncaughtExceptionHandler);
      
   final String cookieTokenAccessName  = "gtasktokenaccess";
   final String cookieTokenRefreshName = "gtasktokenrefresh";
   code = Window.Location.getParameter("code");
   
   final VerticalPanel sp = new VerticalPanel ();
   RootPanel.get().add(sp);
   
   tokenAccess  = Cookies.getCookie(cookieTokenAccessName);
   tokenRefresh = Cookies.getCookie(cookieTokenRefreshName);
   
   if (tokenAccess == null && tokenRefresh == null) {
       if (code != null) {
           Button button = new Button("authenticate", new ClickHandler(){        
               @Override
               public void onClick(ClickEvent event) {            
                   try{
                    gtiService.authenticate(code, new AsyncCallback<Token>() {
                           public void onFailure(Throwable caught) {
                             Window.alert(caught.toString());           
                           }
                           public void onSuccess(Token result) {  
                               token.update(result);                               
                               log.info("token: " + token.toString());  
                               final Date dueDate = new Date();
                               CalendarUtil.addDaysToDate(dueDate, 30); // Cookie will expire in 30 days                                                         
                               Cookies.setCookie(cookieTokenAccessName ,token.getAccess (), dueDate);
                               Cookies.setCookie(cookieTokenRefreshName,token.getRefresh(), dueDate);  
                          }
                       });
                }
                catch(Exception e){                    
                    e.printStackTrace();
                }     
               }
           });
           sp.add(button);  
       }
       else {
           sp.add(new HTML ("no cookie and no authentication code"));                      
       }       
   }
   else {
       token.update(tokenAccess, tokenRefresh);
       final FlexTable flexTable = new FlexTable ();  
       Button button = new Button("get all details", new ClickHandler(){        
          @Override
          public void onClick(ClickEvent event) {       
              log.info("token: " + token.toString());
              gtiService.getList(token, new AsyncCallback<Vector<TaskGrid>>() {
                  public void onFailure(Throwable caught) {
                    Window.alert(caught.toString());           
                  }
                  public void onSuccess(Vector<TaskGrid> result) {                  
                      flexTable.clear ();                  
                      int row = 1;
                      for (TaskGrid taskGrid : result) {
                          int column = new Integer(taskGrid.getLevel()).intValue();
                          flexTable.setWidget(row,column,new HTML (taskGrid.toString()));
                          row++;
                      }                 
                  }
              });      
          }
      });
      sp.add(button);
      sp.add(flexTable); 
   } 

   final Anchor anchor = new Anchor ("renew access"); //TODO add target same window.
   anchor.setTarget("_blank");
   sp.add(anchor);

   gtiService.getAuthorizationUrl(new AsyncCallback<String>() {
       public void onFailure(Throwable caught) {
         Window.alert(caught.toString());           
       }
       public void onSuccess(String result) {           
           anchor.setHref(result);
       }
     });   
  }
}
